<?php

namespace app\admin\controller;

use app\admin\model\Fake;
use app\admin\model\Goods as ModelGoods;
use app\admin\model\GoodsCategory;

class Goods extends Base
{
    public function index()
    {
        return view();
    }
 
    public function add()
    {
        $cateList = GoodsCategory::where('status', 1)->select();
        return view('add', ['cateList' => $cateList]);
    }

    public function doAdd()
    {
        if (request()->isPost()) {
            $param = input();
            if (array_key_exists('vip_time_num', $param)) {
                $param['vip_time'] = Fake::vip_timeStamp($param['vip_time_type'], $param['vip_time_num']);
                unset($param['vip_time_type'], $param['vip_time_num']);
            }
            $hasLikeGood = ModelGoods::where('good_name', $param['good_name'])->findOrEmpty()->isEmpty();
            if (!$hasLikeGood) return error('存在类似商品名称，请注意');
            $res = ModelGoods::create($param);
            if ($res) return success();
            return error();
        }
    }
    public function update()
    {
        $goodId = input('id');
        $cateList = GoodsCategory::where('status', 1)->select();
        $data = ModelGoods::find($goodId);
        return view('update', ['data' => $data,  'cateList' => $cateList]);
    }
    public function list()
    {
        $param = input();
        $good_name = @$param['good_name'];
        if (empty($good_name)) {
            $list = ModelGoods::order('status asc,id desc')->with('category')->paginate($param['limit']);
        } else {
            $list = ModelGoods::where('good_name', 'like', '%' . $good_name . '%')->with(['category'])->order('status asc,id desc')->paginate($param);
        }
        $list = ModelGoods::lisHandel($list);
        return success($list, '操作成功', 0);
    }
    public function doUpdate()
    {
        if (request()->isPost()) {
            $param = input();
            if (array_key_exists('vip_time_num', $param) && !empty($param['vip_time_num'])) {
                $param['vip_time'] = Fake::vip_timeStamp($param['vip_time_type'], $param['vip_time_num']);
                unset($param['vip_time_type'], $param['vip_time_num']);
            }
            $res = ModelGoods::update($param);
            if ($res) return success();
            else return error();
        }
    }
    public function del($id)
    {
        $idArr = explode(',', $id);
        for ($i = 0; $i < count($idArr); $i++) {
            $type = ModelGoods::where('id', $idArr[$i])->value('type');
            if ($type == 1) {
                $goods =  ModelGoods::where('id', $idArr[$i])->with('fake')->find();
                $goods->together(['fake'])->delete();
            }
        }
        // $res = ModelGoods::whereIn('id', $idArr)->delete();
        return success();
    }
}
